package com.example.springboot_springsecurity_jwt_redis.securityHandler;

import com.alibaba.fastjson.JSON;
import com.example.springboot_springsecurity_jwt_redis.common.Result;
import com.example.springboot_springsecurity_jwt_redis.common.ResultCodeEnum;
import com.example.springboot_springsecurity_jwt_redis.utils.DateUtil;
import com.example.springboot_springsecurity_jwt_redis.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登出成功
 */
@Component
@Slf4j
public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {

    // 引入 RedisUtil 工具类
    @Autowired(required = false)
    private RedisUtil redisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        // 获取请求头的 Authorization(授权)
        String authHeader = httpServletRequest.getHeader("Authorization");
        // 判断 Authorization 和 类型Bearer 是否为null
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            final String authToken = authHeader.substring("Bearer ".length());
            //将token放入黑名单中,时间是年月日
            redisUtil.hset("blacklist", authToken, DateUtil.getTime());
            log.info("用户登出成功！token：{}已加入redis黑名单",authToken);
        }
        //返回值
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.result(ResultCodeEnum.RESULT_CODE_USER_LOGOUT_SUCCESS,true)));
    }
}
